using UnityEngine;

public class Player : MonoBehaviour
{
    public GameObject playerBullet;
    public SpriteRenderer sprite;
    private Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        // 监听输入
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");
        if (x > 0)
        {
            sprite.flipX = false;
        }
        else if (x < 0)
        {
            sprite.flipX = true;
        }
        Vector3 move = new Vector3(x, y);
        move = move.normalized;
        // transform.Translate(* Time.deltaTime);
        rb.velocity = move * 5;

        if (Input.GetMouseButtonDown(0))
        {

            Vector3 v = Camera.main.ScreenToViewportPoint(Input.mousePosition);
            v = Camera.main.ViewportToWorldPoint(v);
            Fire(Vector3.Normalize(v - transform.position));
        }
    }


    public void Fire(Vector3 direction)
    {
        // 创建子弹
        GameObject bullet = Instantiate(playerBullet);
        bullet.gameObject.SetActive(true);
        // 设置子弹的位置
        bullet.transform.position = transform.position;
        // 设置子弹的速度
        bullet.GetComponent<PlayerBullet>().direcition = direction;
    }

    public void Hurt(int damage)
    {
        Global.HP -= 1;
        if (Global.HP <= 0)
        {
            Global.HP = 0;
            // 游戏结束
            GameUI.Instance.GameOver.SetActive(true);
            Time.timeScale = 0;
        }
        Global.HPChangedEvent.Invoke();
    }
}
